<template>
  <view class="add-goods">
    <!-- 表单内容 -->
    <uni-forms ref="formRef" :modelValue="formData" :rules="rules" label-position="top">
      <!-- 商品名称 -->
      <uni-forms-item label="商品名称" required name="name">
        <uni-easyinput
          v-model="formData.name"
          placeholder="请输入商品名称"
        />
      </uni-forms-item>

      <!-- 售价 -->
      <uni-forms-item label="售价" required name="price">
        <uni-easyinput
          v-model="formData.price"
          type="number"
          placeholder="请输入商品售价"
        />
      </uni-forms-item>

      <!-- 公司选择 -->
      <uni-forms-item label="公司" required name="supplierId">
        <picker 
          @change="handleSupplierChange" 
          :value="supplierIndex" 
          :range="supplierList" 
          range-key="name"
        >
          <view class="picker-box">
            <text v-if="formData.supplierId">{{ getSupplierName(formData.supplierId) }}</text>
            <text v-else class="placeholder">请选择公司</text>
            <uni-icons type="bottom" size="14" color="#666"/>
          </view>
        </picker>
      </uni-forms-item>

      <!-- 初始库存 -->
      <!-- :disabled="isEdit" -->

      <uni-forms-item label="库存" required name="stock">
        <uni-number-box 
          v-model="formData.stock"
          :min="0"
        />
      </uni-forms-item>

      <!-- 预警值 -->
      <uni-forms-item label="预警值" required name="warningStock">
        <uni-number-box 
          v-model="formData.warningStock"
          :min="0"
        />
        <text class="hint-text">当库存低于此值时将显示预警</text>
      </uni-forms-item>
    </uni-forms>

    <!-- 底部按钮 -->
    <view class="footer">
      <button class="submit-btn" @click="handleSubmit">{{ isEdit ? '保存修改' : '确认添加' }}</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { goodsApi } from '@/api/goods'
import { supplierApi } from '@/api/supplier'

const formRef = ref(null)
const isEdit = ref(false)
const goodsId = ref('')
const supplierIndex = ref(0)
const supplierList = ref([])

// 表单数据
const formData = ref({
  name: '',
  price: '',
  supplierId: '',
  stock: 0,
  warningStock: 10  // 默认预警值为10
})

// 表单校验规则
const rules = {
  name: {
    rules: [{
      required: true,
      errorMessage: '请输入商品名称'
    }]
  },
  price: {
    rules: [{
      required: true,
      errorMessage: '请输入商品售价'
    }]
  },
  supplierId: {
    rules: [{
      required: true,
      errorMessage: '请选择公司'
    }]
  },
  stock: {
    rules: [{
      required: true,
      errorMessage: '请设置初始库存'
    }]
  },
  warningStock: {
    rules: [{
      required: true,
      errorMessage: '请设置库存预警值'
    }]
  }
}

// 获取商品详情
const getGoodsDetail = async (id) => {
  try {
    const res = await goodsApi.getDetail(id)
    const detail = res
    formData.value = {
      name: detail.name,
      price: detail.price,
      supplierId: detail.supplierId,
      stock: detail.stock,
      warningStock: detail.warningStock || 10
    }
    
    // 设置公司选中索引
    const index = supplierList.value.findIndex(item => item.id === detail.supplierId)
    if (index > -1) {
      supplierIndex.value = index
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'error'
    })
  }
}

// 获取公司列表
const getSupplierList = async () => {
  try {
    const res = await supplierApi.getList()
    supplierList.value = res.list || []
    
    // 如果是编辑模式，获取商品详情
    if (isEdit.value) {
      await getGoodsDetail(goodsId.value)
    }
  } catch (error) {
    console.error('获取公司列表失败:', error)
  }
}

// 处理公司选择
const handleSupplierChange = (e) => {
  const index = e.detail.value
  supplierIndex.value = index
  formData.value.supplierId = supplierList.value[index].id
}

// 获取公司名称
const getSupplierName = (id) => {
  const supplier = supplierList.value.find(item => item.id === id)
  return supplier ? supplier.name : ''
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()

    if (isEdit.value) {
      // 更新商品
      await goodsApi.update(goodsId.value, formData.value)
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      })
    } else {
      // 添加商品
      await goodsApi.add(formData.value)
      uni.showToast({
        title: '添加成功',
        icon: 'success'
      })
    }

    // 返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)

  } catch (error) {
    console.error(isEdit.value ? '更新商品失败:' : '添加商品失败:', error)
    uni.showToast({
      title: isEdit.value ? '更新失败' : '添加失败',
      icon: 'error'
    })
  }
}

// 页面加载
onLoad((options) => {
  if (options.id) {
    isEdit.value = true
    goodsId.value = options.id
    // 修改导航栏标题
    uni.setNavigationBarTitle({
      title: '编辑商品'
    })
  }
  // 获取公司列表
  getSupplierList()
})
</script>

<style>
.add-goods {
  min-height: 100vh;
  background-color: #F5F5F5;
  padding: 16px;
  padding-bottom: 80px;
}

/* 表单样式 */
.uni-forms {
  background-color: #fff;
  padding: 16px;
  border-radius: 8px;
}

:deep(.uni-forms-item) {
  margin-bottom: 24px;
}

:deep(.uni-forms-item__label) {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

:deep(.uni-easyinput__content) {
  background-color: #F8FAFC;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  height: 40px;
}

/* 选择器样式 */
.picker-box {
  background-color: #F8FAFC;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  height: 40px;
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.placeholder {
  color: #999;
}

/* 底部按钮 */
.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 16px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}

.submit-btn {
  width: 100%;
  height: 44px;
  background-color: #1890ff;
  color: #fff;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  border: none;
}

.submit-btn:active {
  background-color: #096dd9;
}

.hint-text {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  display: block;
}
</style> 